<template>
  <view class="d-chat">
    <scroll-view :style="{height: state.heightC+'px'}" :scroll-top="state.scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper"
                   @scrolltolower="lower" @scroll="scroll">
        <view :class="item.isself?'self-chat-block':'chat-block'" v-for="(item,index) in state.chatList" :key="index">
          <template v-if="!item.isself">
            <view class="left">
              <u-avatar :src="state.otherSelfInfo.avatar"></u-avatar>
            </view>
            <view class="right">
              <view class="right-text">
                {{item.msg}}
              </view>
            </view>
          </template>
          <template v-else>
            <view class="right">
              <view class="right-text">
                {{item.msg}}
              </view>
            </view>
            <view class="left">
              <u-avatar :src="state.selfInfo.avatar"></u-avatar>
            </view>
          </template>
        </view>

      </scroll-view>
    <view class="bottom-input">
      <view class="input">
        <u-input
            placeholder="请输入内容"
            clearable
            holdKeyboard
            v-model="state.msg"
        >
          <template #prefix>
            <u-icon name="plus-circle-fill" color="#00b169" size="28"></u-icon>
          </template>
          <template #suffix>
            <u-button text="发送" type="success" @click="send"></u-button>

          </template>
        </u-input>
      </view>

    </view>
  </view>
</template>

<script setup>

import {onMounted, reactive} from "vue";
import {onLoad} from "@dcloudio/uni-app";
import {useStore} from "@/pinia/user";
//引入mqtt
import * as mqtt from "mqtt/dist/mqtt.min";
//导入配置
import mqttConfig from "@/config/mqttConfig";
import {getChatRecord, sendMessage} from "@/pages/api/im/im";
//引入解码工具
import {decode} from "@/utils/encodeUtils";

const store = useStore()
const state = reactive({
  heightC: 0,
  selfInfo: {},
  otherSelfInfo: {},
  client: null,
  topic: '',
  msg: '',
  chatList: [
  ],
  scrollTop: 0,
  old: {
    scrollTop: 2000
  },
  page:{
    pageNum:1,
    pageSize:10,
    receiverId:0,
    total:0,
  }
})
onMounted( () => {
  state.heightC = uni.getSystemInfoSync().windowHeight - uni.getSystemInfoSync().statusBarHeight-35;
  mqttConnect();
  //执行的到聊天记录方法
})
//得到聊天记录
const getChatRecordList = async () => {
  const res = await getChatRecord(state.page.receiverId,state.page.pageNum,state.page.pageSize);
  const {data:{records,total,size,current}} = res;
  if (res.code === 20000) {
    state.page.pageNum = current;
    state.page.pageSize = size;
    state.page.total = total;
    records.forEach(item=>{
      state.chatList.unshift({
        isself: item['isSelf'],
        msg: item.content
      })
    })
    state.scrollTop = 2000;
  }
}
const upper= function(e) {
  state.page.pageNum++;
  getChatRecordList();
}
const lower =function(e) {
  console.log(e)
}
const scroll= function(e) {
  console.log(e)
  state.old.scrollTop = e.detail.scrollTop
}
onLoad(async (e) => {
  state.otherSelfInfo = e;
  state.selfInfo = store.getUserInfo
  uni.setNavigationBarTitle({
    title: e.nickname
  })
  state.page.receiverId = e.id;
  await getChatRecordList();

})
const leftClick = () => {
  state.client.end();
}
const mqttConnect = () => {
  state.client = mqtt.connect(mqttConfig.url, {
    clean: true,
    connectTimeout: 100,
    clientId: uni.$u.guid(),
    username: mqttConfig.userName,
    password: mqttConfig.password
  });
  state.client.on("connect", () => {
    const topic = state.otherSelfInfo['id'] + '' + state.selfInfo['id'] + mqttConfig.defaultTopic
    state.topic = topic
    console.log("订阅的主题为", state.topic)
    //订阅主题
    state.client.subscribe(topic, () => {
      console.log("订阅成功")
    });
    state.client.on("message", (topic, message, ss) => {
      state.chatList.push({
        isself: false,
        msg: JSON.parse(decode(message, "utf-8")).content
      })

    });
    // 断开发起重连
    state.client.on("reconnect", (error) => {
      console.log("断线:", error);
    });
    // 链接异常处理
    state.client.on("error", (error) => {
      console.log("异常:", error);
    });
  });
}


const send = () => {
  //有主题前提下
  if (state.topic) {
    if (state.msg!==''){
      sendMessage({
        topic: state.topic,
        content: state.msg,
        fromUserId: state.selfInfo['id'],
        receiveUserId: state.otherSelfInfo['id']
      }).then(() => {
        //推送页面
        state.chatList.push({
          isself: true,
          msg: state.msg
        })
        state.msg = ''
        state.scrollTop=state.chatList.length*100
      })
    }else {
      uni.showToast({title:'请输入内容',icon:'none'})
    }

  }

}

</script>
<style lang="scss">
.d-chat {
  padding: 0 20rpx;
  height: 100%;


  .chat-block {
    margin-top: 20rpx;
    display: flex;
    align-items: center;
    .left {
    }

    .right {
      margin-left: 10rpx;
      .right-text {
        background: #f2f2f2;
        padding: 16rpx;
        font-size: 25rpx;
        border-radius: 10rpx;
        max-width: 80%;
        word-break: break-all;
      }

    }


  }
  .self-chat-block {
    margin-top: 20rpx;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .left {
    }

    .right {
      margin-right: 10rpx;
      display: flex;
      justify-content: flex-end;

      .right-text {
        background: #00b169;
        padding: 16rpx;
        font-size: 25rpx;
        border-radius: 10rpx;
        color: #ffffff;
        max-width: 80%;
        word-break: break-all;
      }

    }


  }
  .bottom-input{
    background-color: #ffffff;
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    padding-bottom: 45rpx;
    display: flex;
    justify-content: center;
    .input{
      width: 95%;
    }

  }

}

</style>

